package cn.com.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;

@Configuration
public class DataSourceConfig {

    @Bean("app")
    public DataSource appDatasource() {
        return DataSourceBuilder.create()
                .url("jdbc:mysql://localhost:3306/db_app")
                .username("root")
                .driverClassName("com.mysql.jdbc.Driver")
                .build();
    }

    @Bean("user")
    public DataSource userDatasource() {
        return new UserRoutingDataSource();
    }

    @Bean
    @Primary
    public DataSource allDataSource(
            @Autowired @Qualifier("app") DataSource app,
            @Autowired @Qualifier("user") DataSource user) {
        AppRoutingDataSource appRoutingDataSource = new AppRoutingDataSource();
        HashMap<Object, Object> dataSourceHashMap = new HashMap<Object, Object>() {{
            put("master", app);
            put("user", user);
        }};
        appRoutingDataSource.setTargetDataSources(dataSourceHashMap);
        return appRoutingDataSource;
    }
}
